package com.czxy.changgou3.filter;

import com.czxy.changgou3.config.FilterProperties;
import com.czxy.changgou3.config.JwtProperties;
import com.czxy.changgou3.pojo.User;
import com.czxy.utils.JwtUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author zhangmengxiang1@itcast.cn
 * @version 1.0
 * @date 2020/4/22
 */
@Component
//加载jwt配置类
@EnableConfigurationProperties({JwtProperties.class , FilterProperties.class} )
public class LoginFilter extends ZuulFilter {
    //2.2 注入jwt配置类实例
    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private FilterProperties filterProperties;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    @Override
    public boolean shouldFilter() {
        //3.1 获取用户请求路径
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();
        //如果报名单中包含此路劲 则跳过
        for (String path : filterProperties.getAllowPaths()) {
            if (requestURI.contains(path)){
                return false;
            }
        }

        //执行 run()方法
        return true;

    }

    @Override
    public Object run() throws ZuulException {
        //获得token
        //获得上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = currentContext.getRequest();
        //获得指定请求头的值
        String token = request.getHeader("Authorization");
        System.out.println(token);
        //校验token--使用Jwt工具类进行解析
        try {
            //使用工具类，通过公钥获得对应信息
            JwtUtils.getObjectFromToken(token,jwtProperties.getPublicKey(), User.class);
        } catch (Exception e) {
            //如果有异常 -- 没有登录 (没有权限)
            currentContext.addOriginResponseHeader("content-type","text/html;charset=UTF-8");
            currentContext.addZuulResponseHeader("content-type","text/html;charset=UTF-8");
            currentContext.setResponseStatusCode( 403 );        //响应的状态码：403
            currentContext.setResponseBody("token失效或无效");
            currentContext.setSendZuulResponse( false );        //没有响应内容
        }
        // 2.5 如果没有异常，登录了--放行
        return null;
    }
}
